<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vision Pro 手部追踪测试</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            min-height: 100vh;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            text-align: center;
        }

        h1 {
            font-size: 2.5em;
            margin-bottom: 30px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .test-section {
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            padding: 30px;
            margin: 20px 0;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .status-success { background-color: #4CAF50; }
        .status-warning { background-color: #FF9800; }
        .status-error { background-color: #F44336; }
        .status-pending { background-color: #9E9E9E; }

        .test-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .test-item:last-child {
            border-bottom: none;
        }

        button {
            background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
            border: none;
            color: white;
            padding: 15px 30px;
            font-size: 18px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }

        button:disabled {
            background: #666;
            cursor: not-allowed;
            transform: none;
        }

        .log-container {
            background: rgba(0,0,0,0.3);
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            text-align: left;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 14px;
        }

        .log-entry {
            margin: 5px 0;
            padding: 5px;
            border-radius: 3px;
        }

        .log-info { background: rgba(33, 150, 243, 0.2); }
        .log-success { background: rgba(76, 175, 80, 0.2); }
        .log-warning { background: rgba(255, 152, 0, 0.2); }
        .log-error { background: rgba(244, 67, 54, 0.2); }

        .hand-data {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin: 20px 0;
        }

        .hand-info {
            background: rgba(255,255,255,0.05);
            border-radius: 10px;
            padding: 15px;
        }

        .gesture-display {
            font-size: 2em;
            margin: 10px 0;
            min-height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #canvas-container {
            position: relative;
            width: 100%;
            height: 400px;
            background: rgba(0,0,0,0.2);
            border-radius: 10px;
            margin: 20px 0;
            overflow: hidden;
        }

        canvas {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🖐️ Vision Pro 手部追踪测试</h1>
        
        <div class="test-section">
            <h2>系统兼容性检测</h2>
            <div id="compatibility-tests">
                <div class="test-item">
                    <span>WebXR 支持</span>
                    <span><span id="webxr-status" class="status-indicator status-pending"></span><span id="webxr-text">检测中...</span></span>
                </div>
                <div class="test-item">
                    <span>手部追踪支持</span>
                    <span><span id="hand-tracking-status" class="status-indicator status-pending"></span><span id="hand-tracking-text">检测中...</span></span>
                </div>
                <div class="test-item">
                    <span>设备类型</span>
                    <span id="device-type">检测中...</span>
                </div>
                <div class="test-item">
                    <span>用户代理</span>
                    <span id="user-agent" style="font-size: 12px; max-width: 300px; word-break: break-all;"></span>
                </div>
            </div>
        </div>

        <div class="test-section">
            <h2>WebXR 会话测试</h2>
            <button id="start-xr-btn" onclick="startXRSession()">启动 WebXR 会话</button>
            <button id="stop-xr-btn" onclick="stopXRSession()" disabled>停止 WebXR 会话</button>
            <div id="session-status">未启动</div>
        </div>

        <div class="test-section">
            <h2>手部追踪数据</h2>
            <div class="hand-data">
                <div class="hand-info">
                    <h3>左手</h3>
                    <div class="gesture-display" id="left-gesture">🤚</div>
                    <div id="left-hand-data">等待数据...</div>
                </div>
                <div class="hand-info">
                    <h3>右手</h3>
                    <div class="gesture-display" id="right-gesture">🤚</div>
                    <div id="right-hand-data">等待数据...</div>
                </div>
            </div>
        </div>

        <div class="test-section">
            <h2>3D 可视化</h2>
            <div id="canvas-container">
                <canvas id="three-canvas"></canvas>
            </div>
        </div>

        <div class="test-section">
            <h2>测试日志</h2>
            <button onclick="clearLog()">清空日志</button>
            <div id="log-container" class="log-container"></div>
        </div>
    </div>

    <script type="module">
        import * as THREE from 'https://unpkg.com/three@0.158.0/build/three.module.js';
        import { VRButton } from 'https://unpkg.com/three@0.158.0/examples/jsm/webxr/VRButton.js';

        // 全局变量
        let scene, camera, renderer, xrSession;
        let leftHandMesh, rightHandMesh;
        let handTrackingSupported = false;

        // 日志系统
        function log(message, type = 'info') {
            const logContainer = document.getElementById('log-container');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.innerHTML = `[${timestamp}] ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        function clearLog() {
            document.getElementById('log-container').innerHTML = '';
        }

        // 设置状态指示器
        function setStatus(elementId, status, text) {
            const indicator = document.getElementById(elementId);
            const textElement = document.getElementById(elementId.replace('-status', '-text'));
            
            indicator.className = `status-indicator status-${status}`;
            if (textElement) textElement.textContent = text;
        }

        // 初始化 Three.js 场景
        function initThreeJS() {
            const container = document.getElementById('canvas-container');
            const canvas = document.getElementById('three-canvas');

            // 场景设置
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x222222);

            // 相机设置
            camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);
            camera.position.set(0, 1.6, 3);

            // 渲染器设置
            renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
            renderer.setSize(container.clientWidth, container.clientHeight);
            renderer.xr.enabled = true;

            // 添加光源
            const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
            scene.add(ambientLight);

            const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
            directionalLight.position.set(1, 1, 1);
            scene.add(directionalLight);

            // 添加地面
            const groundGeometry = new THREE.PlaneGeometry(10, 10);
            const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
            const ground = new THREE.Mesh(groundGeometry, groundMaterial);
            ground.rotation.x = -Math.PI / 2;
            scene.add(ground);

            // 创建手部可视化
            createHandVisualization();

            // 开始渲染循环
            renderer.setAnimationLoop(animate);

            log('Three.js 场景初始化完成', 'success');
        }

        // 创建手部可视化
        function createHandVisualization() {
            // 左手
            const leftHandGeometry = new THREE.SphereGeometry(0.05, 16, 16);
            const leftHandMaterial = new THREE.MeshLambertMaterial({ color: 0x00ff00 });
            leftHandMesh = new THREE.Mesh(leftHandGeometry, leftHandMaterial);
            leftHandMesh.visible = false;
            scene.add(leftHandMesh);

            // 右手
            const rightHandGeometry = new THREE.SphereGeometry(0.05, 16, 16);
            const rightHandMaterial = new THREE.MeshLambertMaterial({ color: 0x0000ff });
            rightHandMesh = new THREE.Mesh(rightHandGeometry, rightHandMaterial);
            rightHandMesh.visible = false;
            scene.add(rightHandMesh);
        }

        // 动画循环
        function animate() {
            if (xrSession && renderer.xr.isPresenting) {
                updateHandTracking();
            }
            renderer.render(scene, camera);
        }

        // 更新手部追踪
        function updateHandTracking() {
            const frame = renderer.xr.getFrame();
            if (!frame) return;

            const referenceSpace = renderer.xr.getReferenceSpace();
            const inputSources = xrSession.inputSources;

            for (const inputSource of inputSources) {
                if (inputSource.hand) {
                    updateHandVisualization(inputSource, frame, referenceSpace);
                }
            }
        }

        // 更新手部可视化
        function updateHandVisualization(inputSource, frame, referenceSpace) {
            const hand = inputSource.hand;
            const handedness = inputSource.handedness;

            try {
                // 获取手腕位置
                const wristJoint = hand.get('wrist');
                if (wristJoint) {
                    const pose = frame.getJointPose(wristJoint, referenceSpace);
                    if (pose) {
                        const mesh = handedness === 'left' ? leftHandMesh : rightHandMesh;
                        mesh.position.copy(pose.transform.position);
                        mesh.quaternion.copy(pose.transform.orientation);
                        mesh.visible = true;

                        // 更新UI显示
                        updateHandDataDisplay(handedness, pose);
                    }
                }
            } catch (error) {
                log(`手部追踪更新错误: ${error.message}`, 'error');
            }
        }

        // 更新手部数据显示
        function updateHandDataDisplay(handedness, pose) {
            const dataElement = document.getElementById(`${handedness}-hand-data`);
            const gestureElement = document.getElementById(`${handedness}-gesture`);
            
            const position = pose.transform.position;
            const orientation = pose.transform.orientation;
            
            dataElement.innerHTML = `
                位置: (${position.x.toFixed(3)}, ${position.y.toFixed(3)}, ${position.z.toFixed(3)})<br>
                旋转: (${orientation.x.toFixed(3)}, ${orientation.y.toFixed(3)}, ${orientation.z.toFixed(3)}, ${orientation.w.toFixed(3)})
            `;

            // 简单的手势检测（基于位置）
            if (position.y > 1.8) {
                gestureElement.textContent = '👋'; // 挥手
            } else if (position.y < 1.2) {
                gestureElement.textContent = '👇'; // 指向下方
            } else {
                gestureElement.textContent = '🤚'; // 默认
            }
        }

        // 检测系统兼容性
        async function checkCompatibility() {
            log('开始系统兼容性检测...', 'info');

            // 检测用户代理
            document.getElementById('user-agent').textContent = navigator.userAgent;

            // 检测设备类型
            const deviceType = detectDeviceType();
            document.getElementById('device-type').textContent = deviceType;
            log(`检测到设备类型: ${deviceType}`, 'info');

            // 检测 WebXR 支持
            if ('xr' in navigator) {
                setStatus('webxr-status', 'success', '支持');
                log('WebXR API 可用', 'success');

                // 检测手部追踪支持
                try {
                    const supported = await navigator.xr.isSessionSupported('immersive-vr');
                    if (supported) {
                        setStatus('hand-tracking-status', 'success', '支持');
                        handTrackingSupported = true;
                        log('手部追踪功能支持', 'success');
                    } else {
                        setStatus('hand-tracking-status', 'warning', '不支持');
                        log('手部追踪功能不支持', 'warning');
                    }
                } catch (error) {
                    setStatus('hand-tracking-status', 'error', '检测失败');
                    log(`手部追踪检测失败: ${error.message}`, 'error');
                }
            } else {
                setStatus('webxr-status', 'error', '不支持');
                setStatus('hand-tracking-status', 'error', '不可用');
                log('WebXR API 不可用', 'error');
            }
        }

        // 检测设备类型
        function detectDeviceType() {
            const userAgent = navigator.userAgent.toLowerCase();
            
            if (userAgent.includes('vision')) {
                return 'Apple Vision Pro';
            } else if (userAgent.includes('quest')) {
                return 'Meta Quest';
            } else if (userAgent.includes('pico')) {
                return 'Pico VR';
            } else if (userAgent.includes('vive')) {
                return 'HTC Vive';
            } else {
                return '未知设备';
            }
        }

        // 启动 WebXR 会话
        window.startXRSession = async function() {
            if (!handTrackingSupported) {
                log('手部追踪不支持，无法启动会话', 'error');
                return;
            }

            try {
                log('请求 WebXR 会话...', 'info');
                
                const sessionInit = {
                    requiredFeatures: ['local-floor'],
                    optionalFeatures: ['hand-tracking', 'dom-overlay'],
                    domOverlay: { root: document.body }
                };

                xrSession = await navigator.xr.requestSession('immersive-vr', sessionInit);
                
                log('WebXR 会话启动成功', 'success');
                document.getElementById('session-status').textContent = '会话已启动';
                document.getElementById('start-xr-btn').disabled = true;
                document.getElementById('stop-xr-btn').disabled = false;

                // 设置会话
                await renderer.xr.setSession(xrSession);

                // 监听会话结束
                xrSession.addEventListener('end', onSessionEnd);

                // 检查启用的功能
                checkEnabledFeatures();

            } catch (error) {
                log(`WebXR 会话启动失败: ${error.message}`, 'error');
                document.getElementById('session-status').textContent = `启动失败: ${error.message}`;
            }
        };

        // 停止 WebXR 会话
        window.stopXRSession = function() {
            if (xrSession) {
                xrSession.end();
            }
        };

        // 会话结束处理
        function onSessionEnd() {
            log('WebXR 会话已结束', 'info');
            document.getElementById('session-status').textContent = '会话已结束';
            document.getElementById('start-xr-btn').disabled = false;
            document.getElementById('stop-xr-btn').disabled = true;
            
            // 隐藏手部可视化
            if (leftHandMesh) leftHandMesh.visible = false;
            if (rightHandMesh) rightHandMesh.visible = false;
            
            xrSession = null;
        }

        // 检查启用的功能
        function checkEnabledFeatures() {
            if (!xrSession) return;

            const enabledFeatures = xrSession.enabledFeatures || [];
            log(`启用的功能: ${enabledFeatures.join(', ')}`, 'info');

            if (enabledFeatures.includes('hand-tracking')) {
                log('手部追踪功能已启用', 'success');
            } else {
                log('手部追踪功能未启用', 'warning');
            }
        }

        // 页面加载完成后初始化
        window.addEventListener('load', () => {
            log('页面加载完成，开始初始化...', 'info');
            initThreeJS();
            checkCompatibility();
        });

        // 窗口大小改变时调整渲染器
        window.addEventListener('resize', () => {
            const container = document.getElementById('canvas-container');
            camera.aspect = container.clientWidth / container.clientHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(container.clientWidth, container.clientHeight);
        });

        // 导出到全局作用域
        window.clearLog = clearLog;
    </script>
</body>
</html>